package com.monas.client.dialog;

import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.monas.client.database.MonasResourceDatabase;
import com.monas.client.util.UIHelper;

public class AddUserDialog extends AbstractUserDialog {

	private static final String MESSAGE = "Please specify new username and password";

	private List<Object[]> users;

	private CCombo combo;

	private Text remarkText;

	private String remark = null;

	private String[] types = { "Common", "Admin" };

	private boolean isAdmin = false;

	public AddUserDialog(Shell parentShell) {
		super(parentShell, "Add User Form");
	}

	@Override
	protected Control createContents(Composite parent) {
		Control contents = createNewContents(parent, MESSAGE);

		/*
		 * Dapatkan data user yang sekarang ada di database.
		 */
		try {
			MonasResourceDatabase source = MonasResourceDatabase.getInstance();
			users = source.getAllUser();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return contents;
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		composite.setLayoutData(UIHelper.fillBoth());
		composite.setLayout(new GridLayout(1, false));

		createUsername(composite);

		createPassword(composite);

		Label label = new Label(composite, SWT.None);
		label.setText("User Type:");

		combo = new CCombo(composite, SWT.BORDER | SWT.READ_ONLY);
		combo.setLayoutData(UIHelper.fillHorizontal());
		combo.setItems(types);
		combo.select(0);
		combo.setEditable(false);

		label = new Label(composite, SWT.None);
		label.setText("Remark:");

		remarkText = createText(composite);
		remarkText.addModifyListener(new ModifyListener() {

			@Override
			public void modifyText(ModifyEvent e) {
				remark = remarkText.getText();
			}
		});

		return composite;
	}

	@Override
	protected void checkCompleted() {
		setErrorMessage(null);
		setMessage(MESSAGE);
		super.checkCompleted();

		if (ok.isEnabled()) {
			isAdmin = types[1].equals(combo.getText());

			for (Object[] fields : users) {
				if (fields[0].equals(getUsername())) {
					error("Username is exist, define another username!");
					return;
				}
			}
		}
	}

	public boolean isAdmin() {
		return isAdmin;
	}

	public String getRemark() {
		if (remark == null) {
			remark = "";
		}
		return remark;
	}
}
